package com.mentorgen.tools.profile.runtime.jar;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;

public class CreateInstBundleJar {
	
	public static void run(String inputDirectory, String outputDirectory, String jarname) throws IOException {
		
	  JarOutputStream target = new JarOutputStream(new FileOutputStream(outputDirectory + System.getProperty("file.separator") + jarname));
	  File inputDir = new File(inputDirectory); 
	  if (!inputDir.isDirectory())
		  throw new IOException("The Specified InputDirectory is not a directory.");
	  
	  for (File file : inputDir.listFiles())
		  add(file, target, null);
	  target.close();
	}

	private static void add(File source, JarOutputStream target, String path) throws IOException
	{
		  BufferedInputStream in = null;
		  String name = (path == null) ? "" : (path + source.getName()) + System.getProperty("file.separator");
		  
		  try
		  {
			if (source.isDirectory())
			{
			  if (!name.isEmpty()) {
				  
				  if (!name.endsWith("/"))
					  name += "/";
				  
			    JarEntry entry = new JarEntry(name);
			    entry.setTime(source.lastModified());
			    target.putNextEntry(entry);
			    target.closeEntry();
			  }
			  
			  for (File nestedFile: source.listFiles())
			    add(nestedFile, target, path + System.getProperty("file.separator") + source.getName());
			  return;
			}
		
			JarEntry entry = new JarEntry(name.replace("\\", "/"));
		    entry.setTime(source.lastModified());
		    target.putNextEntry(entry);
		    in = new BufferedInputStream(new FileInputStream(source));
		
		    byte[] buffer = new byte[1024];
		    while (true){
		      int count = in.read(buffer);
		      if (count == -1)
		        break;
		      target.write(buffer, 0, count);
		    }
		    target.closeEntry();
		    
		  }finally {
		    if (in != null)
		      in.close();
		  }
		}
}
